package util;


import org.apache.ibatis.io.Resources;


import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 邮件发送工具类
 */
public class MailUtil {
    private static Properties properties;
    private static Message msg;
    private static Transport transport;
    //初始化Mail信息
    private static void init(){
        properties = new Properties();
        InputStream resource = null;
        try {
            resource = Resources.getResourceAsStream("mail.properties");
            properties.load(resource);
            Session session = Session.getInstance(properties);
            msg = new MimeMessage(session);
            msg.setSubject("fly社区邮箱验证");
            //设置发件人
            msg.setFrom(new InternetAddress(properties.getProperty("mail.user")));
            transport = session.getTransport();
            //设置发件人在该邮箱主机上的用户名密码
            transport.connect(properties.getProperty("mail.user"), properties.getProperty("mail.password"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            if(resource!=null){
                try {
                    resource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
    /**
     * 得到邮箱地址邮箱内容发送。
     * @param address 邮箱地址
     * @param text 邮箱内容
     * @throws AddressException
     * @throws MessagingException
     */

    public static boolean sendMail(String address ,String text){
        init();
        try {
            msg.setText(text);
            transport.sendMessage(msg, new Address[] {new InternetAddress(address)});
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (transport.isConnected()){
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
